import userInfoLess from "./userInfo.module.less";
import { DatePicker, Form, Input, message, Select, Upload } from "antd";
import { CloseOutlined, PlusCircleOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { UploadApi } from "@/http/api/upload";
import dayjs from "dayjs";
import ImgCrop from "antd-img-crop";
import { UserInfoType } from "./type/userInfoType";
import {
  GetIntertesLabelListApi,
  GetWorkDirectionListApi,
  GetUserInfoApi,
  SaveUserInfoApi,
} from "@/http/api/setting";
import type { GetProp, UploadFile, UploadProps, FormProps } from "antd";
const formItemLayout = {
  labelCol: {
    sm: { span: 4 },
  },
};
const fieldNames = {
  label: "WorkName",
  value: "Id",
};
type FieldType = {
  UserName?: string;
  ActionWorkTime?: string;
  WorkId?: number;
  WorkName?: string;
  Company?: string;
  MyHomeUrl?: string;
  SelfDescription?: string;
  IntertesTab?: string[];
};

function UserInfo() {
  const [form] = Form.useForm();
  const [intertesLable, setIntertesLable] = useState([]);
  const [workDirection, setWorkDirection] = useState([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [userInfo, setUserInfo] = useState<UserInfoType>({
    HeaderImg: "",
  });
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [selectLabelList, setSelectLabelList]: any = useState([]);
  const GetIntertesList = async () => {
    const res: any = await GetIntertesLabelListApi();
    console.log("获取到兴趣标签列表", res);
    setIntertesLable(res.intertesLabelList);
  };
  const GetWorkDirectionList = async () => {
    const res: any = await GetWorkDirectionListApi();
    console.log("获取到工作方向列表", res);
    setWorkDirection(res.workDirectionList);
  };
  const GetUserInfo = async () => {
    const res: any = await GetUserInfoApi();
    console.log("获取到用户信息", res);
    setUserInfo(res.UserInfo);
    form.setFieldsValue({
      UserName: res.UserInfo.UserName,
      ActionWorkTime: dayjs(res.UserInfo.ActionWorkTime, "YYYY-MM"),
      WorkId: res.UserInfo.WorkId,
      WorkName: res.UserInfo.WorkName,
      Company: res.UserInfo.Company,
      MyHomeUrl: res.UserInfo.MyHomeUrl,
      SelfDescription: res.UserInfo.SelfDescription,
      IntertesTab: res.UserInfo.IntertesTab,
    });
    setSelectLabelList(res.UserInfo.IntertesTab);
  };
  const selectLikeLabel = (item: any) => {
    console.log(item, "item");
    if (selectLabelList.includes(item.LabelName)) {
      setSelectLabelList((prev: any) =>
        prev.filter((itemTow: any) => itemTow !== item.LabelName)
      );
    } else {
      setSelectLabelList((prev: any) => [...prev, item.LabelName]);
    }
    /*     console.log(333, selectLabelList); */
  };
  const changeHeaderImg = () => {
    console.log("修改头像");
  };
  const saveChange = () => {
    form.submit();
  };
  const onFinish: FormProps<FieldType>["onFinish"] = async (values) => {
    console.log("Success:", values);
    const formData = form.getFieldsValue();
    console.log("保存修改并已经通过校验", formData);
    const params = {
      UserName: formData.UserName,
      ActionWorkTime: formData.ActionWorkTime?.format("YYYY-MM"),
      WorkId: formData.WorkId,
      WorkName: formData.WorkName,
      Company: formData.Company,
      MyHomeUrl: formData.MyHomeUrl,
      SelfDescription: formData.SelfDescription,
      IntertesTab: formData.IntertesTab.join(","),
      HeaderImg: userInfo.HeaderImg,
    };
    const res: any = await SaveUserInfoApi(params);
    console.log("提交保存结果", res);
    if (res.status === 0) {
      messageApi.open({
        type: "success",
        content: "保存修改成功~",
      });
    }
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };
  const handlePreview = async (file: any) => {
    const form = new FormData();
    form.append("file", file.file);
    const res: any = await UploadApi(form);
    console.log("上传结果", res);
    if (res.status === 0) {
      setUserInfo({ ...userInfo, HeaderImg: res.url });
    }
    return false;
  };
  const checkSelectTab = () => {
    if (selectLabelList.length === 0) {
      return Promise.reject(new Error("请选择兴趣标签"));
    } else {
      return Promise.resolve();
    }
  };
  useEffect(() => {
    form.setFieldValue("IntertesTab", selectLabelList);
  }, [selectLabelList]);
  useEffect(() => {
    GetIntertesList();
    GetWorkDirectionList();
    GetUserInfo();
  }, []);
  return (
    <>
      {contextHolder}
      <div className={userInfoLess.userInfoContent}>
        <div className="topTitle">个人资料</div>
        <div className="bottomInfo">
          <div className="leftInfo">
            <Form
              {...formItemLayout}
              colon={false}
              form={form}
              variant={"filled"}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <div className="baseInfo">
                <div className="tabTitle">基本信息</div>
                <div className="form">
                  <Form.Item
                    label="用户名"
                    name="UserName"
                    rules={[{ required: true, message: "请输入用户名" }]}
                  >
                    <Input
                      placeholder="请输入用户名"
                      showCount
                      maxLength={20}
                    />
                  </Form.Item>

                  <Form.Item
                    label="开始工作"
                    name="ActionWorkTime"
                    rules={[{ required: true, message: "请选择开始工作时间" }]}
                  >
                    <DatePicker picker="month" style={{ width: "100%" }} />
                  </Form.Item>

                  <Form.Item
                    label="职业方向"
                    name="WorkId"
                    rules={[{ required: true, message: "请选择职业方向" }]}
                  >
                    <Select
                      fieldNames={fieldNames}
                      options={workDirection}
                      placeholder="请选择你的职业方向"
                    />
                  </Form.Item>

                  <Form.Item label="职位" name="WorkName">
                    <Input
                      style={{ width: "100%" }}
                      showCount
                      maxLength={50}
                      placeholder="请输入你的职位名称"
                    />
                  </Form.Item>

                  <Form.Item label="公司" name="Company">
                    <Input
                      style={{ width: "100%" }}
                      showCount
                      maxLength={50}
                      placeholder="请输入你的公司"
                    />
                  </Form.Item>

                  <Form.Item label="个人主页" name="MyHomeUrl">
                    <Input
                      style={{ width: "100%" }}
                      showCount
                      maxLength={100}
                      placeholder="请输入你的个人主页"
                    />
                  </Form.Item>

                  <Form.Item label="个人介绍" name="SelfDescription">
                    <Input.TextArea
                      showCount
                      maxLength={100}
                      placeholder="请填写职业技能，擅长的事情，兴趣爱好等"
                    />
                  </Form.Item>
                </div>
              </div>
              <div className="baseInfo">
                <div className="tabTitle">兴趣标签管理</div>
                <div className="form">
                  <Form.Item
                    label="兴趣标签"
                    name="IntertesTab"
                    rules={[{ validator: checkSelectTab, required: true }]}
                  >
                    <div className="rightLike">
                      <div className="likeTabContent">
                        {selectLabelList.map((item: any, index: number) => {
                          return (
                            <div className="tabs" key={index}>
                              <div className="leftValue">{item}</div>
                              <div className="close">
                                <CloseOutlined />
                              </div>
                            </div>
                          );
                        })}
                      </div>
                      <div className="allLikeSelect">
                        {intertesLable.map((item: any, index: number) => {
                          return (
                            <div
                              className={[
                                "likes",
                                selectLabelList.includes(item.LabelName)
                                  ? "likesActive"
                                  : "",
                              ].join(" ")}
                              key={index}
                              onClick={() => selectLikeLabel(item)}
                            >
                              {item.LabelName}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  </Form.Item>
                  <Form.Item label=" ">
                    <div className="submitBtn" onClick={saveChange}>
                      保存修改
                    </div>
                  </Form.Item>
                </div>
              </div>
            </Form>
          </div>
          <div className="rightHeaderImg">
            <ImgCrop rotationSlider cropShape={"round"}>
              <Upload
                accept="image/*"
                fileList={fileList}
                onChange={onChange}
                customRequest={handlePreview}
                maxCount={1}
                showUploadList={false}
              >
                <div className="header">
                  <img src={userInfo.HeaderImg} alt="" />
                  <div className="overlay" onClick={changeHeaderImg}>
                    <div className="topIcon">
                      <PlusCircleOutlined />
                    </div>
                    <div className="title">点击修改头像</div>
                  </div>
                </div>
              </Upload>
            </ImgCrop>
            <div className="tips">上传头像</div>
            <div className="tipsLitter">
              格式：支持JPG、PNG、GIF，大小不超过5M
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

export default UserInfo;
